<?php
	include('db-api/txt-db-api.php');
	
	function email_found($db)
	{
		$username = $_SESSION['username'];
		$rs = $db->executeQuery('SELECT * FROM Users WHERE Email = \'' . $_POST['email'] . '\' AND Username != \''
		. $username . '\'');
		if($rs->next())
		{
			return true;
		}
		return false;
	}
	
	function change_profile(&$error, &$success, &$name, &$surname, &$email, &$password)
	{
		if(!isset($_POST['firstname']) || $_POST['firstname'] == '')
			$error = '* Δε δώσατε όνομα<br />';
		if(!isset($_POST['lastname']) || $_POST['lastname'] == '')
			$error = $error . '* Δε δώσατε επώνυμο<br />';
		if(!isset($_POST['password']) || $_POST['password'] == '')
			$error = $error . '* Δε δώσατε συνθηματικό<br />';
		if(!isset($_POST['email']) || $_POST['email'] == '')
			$error = $error . '* Δε δώσατε ηλεκτρονική διεύθυνση<br />';
			
		if($error != '')
			return;

		$db = new Database('Eclass');
		if(email_found($db) == true)
			$error = $error . '* Η ηλεκτρονική διεύθυνση υπάρχει ήδη';
						
		if($error != '')
			return;
		
		$name = $_POST['firstname'];
		$surname = $_POST['lastname'];
		$email = $_POST['email'];
		$password = $_POST['password'];	
		$db->executeQuery('UPDATE Users SET Name = \'' . $name . '\', Surname = \'' . $surname .
		'\', Email = \'' . $email . '\', Password = \'' . $password . '\' WHERE Username = \'' . $_SESSION['username']
		. '\'');
		$_SESSION['user'] = $name . ' ' . $surname;
		
		$success = 'Η αλλαγή έγινε με επιτυχία';
	}
	
	$username = $_SESSION['username'];
	if($_SESSION['position'] == 'Admin')
		$pos = 'Διαχειριστής';
	else if($_SESSION['position'] == 'Prof')
		$pos = 'Καθηγητής';
	else
		$pos = 'Φοιτητής';

	$db = new Database('Eclass');
	$rs = $db->executeQuery('SELECT Name, Surname, Email, Password FROM Users WHERE Username = \'' . $username . '\'');
	$rs->next();
	list($name, $surname, $email, $password) = $rs->getCurrentValues();
	
	$error = '';
	$success = '';
	if(isset($_GET['action']) && $_GET['action'] == 'change')
		change_profile($error, $success, $name, $surname, $email, $password);
?>
